var fs = require('fs'),
    path = require('path'),
    marked = require('marked'),
    mustache = require('mustache');

var homeTpl,
    postTpl,
    dirs,
    homePosts = [];

function init() {

    /**
     *  _layout for site layout mustache files
     *  _posts for post articles
     *  _html for generate html files
     */
    dirs = {
        tmpl: path.resolve(__dirname, '_layout'),
        post: path.resolve(__dirname, '_posts'),
        html: path.resolve(__dirname, '_html')
    };

    for (var dir in dirs) {
        console.log(dirs[dir]);
        if (!fs.existsSync(dirs[dir])) {
            console.log('[ERROR] ', dirs[dir], ' directory do not exist');
            return false;
        }
    }

    // reading templates form _layouts directory
    homeTmpl = fs.readFileSync(path.resolve(dirs.tmpl, 'home.mst'), 'utf-8');
    postTmpl = fs.readFileSync(path.resolve(dirs.tmpl, 'post.mst'), 'utf-8');

    return true;
}

function writeFile(fileName, contents) {

    fs.writeFile(fileName, contents, function (err) {
        if (err) {
            console.log('[ERROR] while generate ', fileName);
        } else {
            console.log("[SUCC] generate " + fileName);
        }
    });
}

function getPostInfo(content) {

    var header, title, data, tags;

    // get the post's title
    header = /title:\s+(.+)/.exec(content);
    title = header[1].substr(1, header[1].length-2);
    
    // get the post's date
    header = /date:\s+(.+)/.exec(content);
    date = header[1];

    // get the post's tags
    header = /tags:\s+(.+)/.exec(content);
    tags = header[1].substr(1, header[1].length-2);

    return {
        title: title,
        date: date,
        tags: tags
    };
}

function convertMKD2HTML(post) {

    var mkdFile, htmlFile,
        content, postInfo, html;       

    // input and output files
    mkdFile = path.resolve(dirs.post, post);
    htmlFile = path.resolve(dirs.html, post.replace(/md/, 'html'));
 
    // read the content of the post
    content = fs.readFileSync(mkdFile, "utf-8");

    // get the title, date, tags info of post
    postInfo = getPostInfo(content);

    // remove title, date and tags info from contents
    content = content.substr(content.indexOf('---', 4) + 4);

    // to generate the html file
    html = mustache.render(postTmpl, {
        content: marked(content)
    });
    writeFile(htmlFile, html);

    return postInfo;
}

function build() {

    var posts = fs.readdirSync(dirs.post),
        indexHTML;

    // generate notes
    fs.readdir(dirs.post, function (err, posts) {

        if (err) {
            console.log('[ERROR] while reading posts');
            return;
        }

        posts.forEach(function (post) {

            var postInfo,
                tagList,
                className,
                tags = [];

            postInfo = convertMKD2HTML(post);

            tagList = postInfo.tags.split(',');
            className = [];

            for (var i = 0, len = tagList.length; i < len; i++) {
                tagList[i].trim();
                tags.push({ 
                    tagName: tagList[i]
                });
                className.push(tagList[i]);
            }

            homePosts.push({
                className: className.join(' '),
                date: postInfo.date,
                url: './_html/' + post.replace(/md/, 'html'),
                title: postInfo.title,
                tags: tags
            });
        });        

        // generate index.html
        var indexHTML = mustache.render(homeTmpl, {
            posts: homePosts
        });
        writeFile(path.resolve(__dirname, 'index.html'), indexHTML);
    });
}

// Main Entry
;(function () {

    if (init() === true) {
        build();
    }

})();